<script setup lang="ts">
import { ref } from "vue";
import { useGeocoder, usePoint, getPointByAddress } from "vue-baidu-map-3x"; // 引入函数

const emit = defineEmits(["onAddress"]); // 声明自定义事件
// 数据
const visible = ref(false); // 弹窗是否显示
const center = ref({ lng: 121.4899, lat: 31.3989 }); // 地图中心点
const isShow = ref(false); // 是否只是展示

// 函数
const show = async (item: any, show: boolean) => {
  isShow.value = show;
  if (item) {
    // 去获取经纬度
    // console.log(item.value.address);
    
    const res: any = await getPointByAddress({ address: item.value.address }, [
      "pp7tZwclxHhXPTfrgggiTCGIw5u1bqAm",
    ]);
    if (res) {
      center.value = res.location;
    }
  }
  visible.value = true;
};
const show2 = async (item: any, show: boolean) => {
  isShow.value = show;
  if (item) {
    // 去获取经纬度
    console.log(item.address);
    
    // console.log(1112222333);
    
    const res: any = await getPointByAddress({ address: item.address }, [
      "pp7tZwclxHhXPTfrgggiTCGIw5u1bqAm",
    ]);
    console.log(res);
    
    if (res) {
      center.value = res.location;
    }
  }
  visible.value = true;
  // console.log(1111111);
  
};

const dragend = (e: any) => {
  // 去监听bm-marker拖动事件
  // console.log('=================e', e);
  center.value = e.point; // 将拖动结束时的经纬度保存在center中
};
const click = (e: any) => {
  // console.log('=================e', e);
  center.value = e.point;
};
const confirm = async () => {
  useGeocoder().then((geocoder:any) => {
    // longtitude latitude
    usePoint(center.value.lng, center.value.lat).then((point:any) => {
      geocoder.getLocation(point, (result: any) => {
        console.log(result.address);
        visible.value = false;
        emit("onAddress", result.address);
        
      });
    });
  });
};

defineExpose({ show,show2 }); // 暴露函数让其他组件调用，并且defineExpose不需要引入
</script>

<template>
  <!-- 如果需要重新加载组件，使用v-if把组件删除掉 -->
  <el-dialog v-model="visible" title="地图展示" v-if="visible">
    <div class="container">
      <baidu-map class="map" :center="center" :zoom="15" scroll-wheel-zoom @click="click">
        <!-- 去监听拖动事件，获取到marker的最终位置 -->
        <bm-marker @dragend="dragend" :position="center" :dragging="true" animation="BMAP_ANIMATION_BOUNCE">
        </bm-marker>
        <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_PERSPECTIVE_MAP', 'BMAP_SATELLITE_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-map-type>
      </baidu-map>
    </div>
    <template #footer v-if="!isShow">
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="confirm()">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.container {
  height: 500px;
}
.map {
  width: 100%;
  height: 100%;
}
</style>